<template>
    <div class="service-image-preview">
        <div class="large-image-list">
            <img :src="activeImage?.url || defaultImgSrc" />
        </div>
        <ul class="thumbnail-list">
            <li v-for="(image, index) in imageList" :key="index" :class="{ active: activeImageIndex === index }">
                <div
                    :style="{ backgroundImage: `url(${image.url || defaultImgSrc})` }"
                    class="thumbnail-item"
                    @click="previewThumbnail(index)"
                ></div>
            </li>
        </ul>
    </div>
</template>

<script lang="ts" setup>
import { getImage } from '@/api/api.upload';
import { computed, ref, watch } from 'vue';

const props = defineProps({
    imgSrc: {
        type: String,
    }
});  

const defaultImgSrc = require('@/assets/image/image_default@2x.png');
const urlRef = ref('')
const imageList = ref([
    {
        url: urlRef,
    },
    {
        url: defaultImgSrc,
    },
]);
const activeImageIndex = ref(0);
const activeImage = computed(() => imageList.value[activeImageIndex.value]);

watch(() => props.imgSrc, (val) => {
    if (val) {
        getImage(val).then(res => {
            if (res.data.type !== 'application/json') {
                urlRef.value = URL.createObjectURL(res.data)
            }
            else {
                urlRef.value = ''
            }
        })
    }
    else {
        urlRef.value = ''
    }
}, { immediate: true })
  

function previewThumbnail(index: number) {
    activeImageIndex.value = index;
}
</script>

<style scoped>
.service-image-preview {
    width: 100%;
}

.large-image-list {
    position: relative;
    box-sizing: content-box;
    width: 100%;
    height: 0;
    padding-bottom: 100%;
    margin-bottom: 16px;
}

.large-image-list > img {
    position: absolute;
    display: block;
    box-sizing: content-box;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: var(--border-radius);
    border: 1px solid var(--border-color-transparent);
}

.thumbnail-list {
    display: flex;
    width: 100%;
    overflow: auto;
}

.thumbnail-list > li {
    width: 90px;
    height: 90px;
    padding: 6px;
    border-radius: var(--border-radius);
    flex-shrink: 0;
}

.thumbnail-item {
    width: 100%;
    height: 100%;
    background: url('~@/assets/image/image_default@2x.png') no-repeat center center / cover;
    border-radius: var(--border-radius);
    border: solid 1px var(--primary-color);
    cursor: pointer;
}

.thumbnail-list > li.active .thumbnail-item {
    box-shadow: 0px 0px 6px 0px var(--primary-color);
}
</style>
